<template>
	<view class="container">
		<!-- IP信息 -->
		<view class="ip-info">
			<image class="ip-banner" :src="ipInfo.banner" mode="aspectFill"></image>
			<view class="ip-content">
				<text class="name">{{ipInfo.name}}</text>
				<text class="desc">{{ipInfo.desc}}</text>
			</view>
		</view>
		
		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="search-input">
				<input 
					type="text" 
					v-model="searchKey" 
					placeholder="搜索相关商品" 
					@input="onSearch"
					@focus="showSearchPanel = true"
				/>
				<text class="clear-btn" v-if="searchKey" @tap="clearSearch">×</text>
			</view>
			
			<!-- 搜索面板 -->
			<view class="search-panel" v-if="showSearchPanel">
				<!-- 搜索历史 -->
				<view class="search-section" v-if="searchHistory.length > 0">
					<view class="section-header">
						<text class="title">搜索历史</text>
						<text class="clear" @tap="clearHistory">清空</text>
					</view>
					<view class="tag-list">
						<view 
							class="tag-item" 
							v-for="(item, index) in searchHistory" 
							:key="index"
							@tap="useHistoryItem(item)"
						>{{item}}</view>
					</view>
				</view>
				
				<!-- 热门搜索 -->
				<view class="search-section">
					<view class="section-header">
						<text class="title">热门搜索</text>
					</view>
					<view class="tag-list">
						<view 
							class="tag-item" 
							v-for="(item, index) in hotSearchList" 
							:key="index"
							@tap="useHistoryItem(item)"
						>{{item}}</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 分类标签栏 -->
		<view class="sub-category">
			<view class="category-tags">
				<view 
					class="tag-item" 
					:class="{ active: currentSubCategory === 'all' }"
					@tap="changeSubCategory({id: 'all', name: '全部'})"
				>
					<text>全部</text>
				</view>
				<view 
					class="tag-item" 
					:class="{ active: currentSubCategory === 'figure' }"
					@tap="changeSubCategory({id: 'figure', name: '手办模型'})"
				>
					<text>手办模型</text>
				</view>
				<view 
					class="tag-item" 
					:class="{ active: currentSubCategory === 'manga' }"
					@tap="changeSubCategory({id: 'manga', name: '漫画书籍'})"
				>
					<text>漫画书籍</text>
				</view>
				<view class="tag-item more-btn" @tap="showMoreCategories = true">
					<text>更多</text>
					<text class="arrow-down">▼</text>
				</view>
			</view>
			
			<!-- 更多分类弹窗 -->
			<view class="more-categories" v-if="showMoreCategories" @tap.stop="showMoreCategories = false">
				<view class="mask" @tap.stop="showMoreCategories = false"></view>
				<view class="content" @tap.stop>
					<view class="title">全部分类</view>
					<view class="category-grid">
						<view 
							class="grid-item" 
							:class="{ active: currentSubCategory === item.id }"
							v-for="(item, index) in subCategories" 
							:key="index"
							@tap="selectMoreCategory(item)"
						>
							<text>{{item.name}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 筛选栏 -->
		<view class="filter-bar">
			<view class="filter-item" :class="{ active: currentSort === 'default' }" @tap="changeSort('default')">
				默认
			</view>
			<view class="filter-item" :class="{ active: currentSort === 'price' }" @tap="changeSort('price')">
				价格
				<text class="iconfont" :class="priceSort === 'asc' ? 'icon-up' : 'icon-down'"></text>
			</view>
			<view class="filter-item" :class="{ active: currentSort === 'sales' }" @tap="changeSort('sales')">
				销量
			</view>
		</view>
		
		<!-- 商品列表 -->
		<scroll-view class="product-list" scroll-y @scrolltolower="loadMore">
			<view class="waterfall-wrapper">
				<!-- 左列 -->
				<view class="waterfall-column">
					<view 
						class="product-item" 
						v-for="(item, index) in leftProducts" 
						:key="index"
						@tap="goDetail(item)"
					>
						<image :src="item.image" mode="widthFix"></image>
						<view class="product-info">
							<text class="title">{{item.title}}</text>
							<text class="desc">{{item.desc}}</text>
							<view class="price-box">
								<text class="price">¥{{item.price}}</text>
								<text class="original-price">¥{{item.originalPrice}}</text>
							</view>
							<view class="product-meta">
								<text class="sales">销量 {{item.sales}}</text>
								<text class="stock">库存 {{item.stock}}</text>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 右列 -->
				<view class="waterfall-column">
					<view 
						class="product-item" 
						v-for="(item, index) in rightProducts" 
						:key="index"
						@tap="goDetail(item)"
					>
						<image :src="item.image" mode="widthFix"></image>
						<view class="product-info">
							<text class="title">{{item.title}}</text>
							<text class="desc">{{item.desc}}</text>
							<view class="price-box">
								<text class="price">¥{{item.price}}</text>
								<text class="original-price">¥{{item.originalPrice}}</text>
							</view>
							<view class="product-meta">
								<text class="sales">销量 {{item.sales}}</text>
								<text class="stock">库存 {{item.stock}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			
			<!-- 加载更多 -->
			<view class="loading-more" v-if="hasMore && !searchKey">
				<text>加载中...</text>
			</view>
			<view class="no-more" v-else-if="!hasMore && !searchKey">
				<text>没有更多了</text>
			</view>
			<view class="no-result" v-else-if="searchKey && filteredProducts.length === 0">
				<text>未找到相关商品</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				ipId: null,
				currentSubCategory: 'all',
				subCategories: [
					{ id: 'all', name: '全部' },
					{ id: 'figure', name: '手办模型' },
					{ id: 'manga', name: '漫画书籍' },
					{ id: 'peripheral', name: '周边商品' },
					{ id: 'limited', name: '限定商品' },
					{ id: 'digital', name: '数字内容' }
				],
				searchKey: '',
				showSearchPanel: false,
				searchHistory: [],
				hotSearchList: [],
				ipInfo: {
					name: '',
					desc: '',
					banner: ''
				},
				currentSort: 'default',
				priceSort: 'asc',
				page: 1,
				pageSize: 10,
				productList: [],
				hasMore: true,
				loading: false,
				searchTimer: null,
				showMoreCategories: false
			}
		},
		computed: {
			filteredProducts() {
				if (!this.productList.length) return []
				
				let result = this.productList
				
				// 按子分类筛选
				if (this.currentSubCategory !== 'all') {
					result = result.filter(item => item.categoryType === this.currentSubCategory)
				}
				
				// 按搜索关键词筛选
				if (this.searchKey) {
					const key = this.searchKey.toLowerCase()
					result = result.filter(item => 
						item.title.toLowerCase().includes(key) ||
						item.desc.toLowerCase().includes(key)
					)
				}
				
				return result
			},
			// 左列商品
			leftProducts() {
				return this.filteredProducts.filter((_, index) => index % 2 === 0)
			},
			// 右列商品
			rightProducts() {
				return this.filteredProducts.filter((_, index) => index % 2 === 1)
			}
		},
		onLoad(options) {
			if (options.id) {
				this.ipId = parseInt(options.id)
				this.getIpInfo()
				this.getProductList()
				this.getHotSearch()
				this.loadSearchHistory()
			}
		},
		methods: {
			// 防抖函数：在一段时间内，无论触发多少次事件，都只执行最后一次
			debounce(func, wait) {
				// 清除之前的定时器
				if (this.searchTimer) {
					clearTimeout(this.searchTimer)
				}
				
				// 设置新的定时器
				this.searchTimer = setTimeout(() => {
					func()
				}, wait)
			},
			// 获取IP信息
			getIpInfo() {
				// TODO: 调用接口获取IP信息
				// 模拟数据
				const ipMap = {
					1: { name: '鬼灭之刃', desc: '热门动漫IP', banner: '/static/ip/kimetsu-banner.jpg' },
					2: { name: '咒术回战', desc: '热门动漫IP', banner: '/static/ip/jujutsu-banner.jpg' },
					3: { name: '海贼王', desc: '经典动漫IP', banner: '/static/ip/onepiece-banner.jpg' },
					4: { name: '进击的巨人', desc: '经典动漫IP', banner: '/static/ip/titan-banner.jpg' },
					5: { name: 'Fate系列', desc: '人气游戏IP', banner: '/static/ip/fate-banner.jpg' },
					6: { name: '初音未来', desc: '虚拟歌姬IP', banner: '/static/ip/miku-banner.jpg' },
					7: { name: '东方Project', desc: '二次元游戏IP', banner: '/static/ip/touhou-banner.jpg' },
					8: { name: 'EVA', desc: '经典动漫IP', banner: '/static/ip/eva-banner.jpg' },
					9: { name: '周杰伦', desc: '华语流行天王', banner: '/static/ip/jay-banner.jpg' },
					10: { name: '五月天', desc: '华语摇滚天团', banner: '/static/ip/mayday-banner.jpg' },
					11: { name: '漫威英雄', desc: '欧美超级英雄IP', banner: '/static/ip/marvel-banner.jpg' },
					12: { name: 'DC英雄', desc: '欧美超级英雄IP', banner: '/static/ip/dc-banner.jpg' }
				}
				this.ipInfo = ipMap[this.ipId] || { name: '未知IP', desc: '', banner: '/static/ip/default-banner.jpg' }
			},
			// 获取商品列表
			getProductList() {
				if (this.loading || !this.hasMore) return
				
				this.loading = true
				// TODO: 调用接口获取商品列表
				// 模拟数据
				setTimeout(() => {
					const categoryTypes = ['figure', 'manga', 'peripheral', 'limited', 'digital']
					const mockData = Array(this.pageSize).fill().map((_, index) => ({
						id: (this.page - 1) * this.pageSize + index + 1,
						title: `${this.ipInfo.name} ${['手办', '漫画', '周边', '限定'][Math.floor(Math.random() * 4)]} ${(this.page - 1) * this.pageSize + index + 1}`,
						desc: `${this.ipInfo.name}正版授权商品`,
						price: (Math.random() * 1000).toFixed(2),
						originalPrice: (Math.random() * 2000).toFixed(2),
						image: '/static/product/product1.jpg',
						sales: Math.floor(Math.random() * 1000),
						stock: Math.floor(Math.random() * 100),
						categoryType: categoryTypes[Math.floor(Math.random() * categoryTypes.length)]
					}))
					
					this.productList = [...this.productList, ...mockData]
					this.page++
					this.hasMore = this.page <= 3 // 模拟只有3页数据
					this.loading = false
				}, 500)
			},
			// 获取热门搜索
			async getHotSearch() {
				try {
					// TODO: 从后端获取热门搜索数据
					// 模拟数据
					this.hotSearchList = ['限定手办', '漫画全集', '周边新品', '联名款']
				} catch (e) {
					console.error('获取热门搜索失败：', e)
				}
			},
			// 加载搜索历史
			loadSearchHistory() {
				try {
					const history = uni.getStorageSync('searchHistory') || '[]'
					this.searchHistory = JSON.parse(history)
				} catch (e) {
					console.error('加载搜索历史失败：', e)
					this.searchHistory = []
				}
			},
			// 保存搜索历史
			saveSearchHistory() {
				if (!this.searchKey) return
				
				const key = this.searchKey.trim()
				const index = this.searchHistory.indexOf(key)
				if (index > -1) {
					this.searchHistory.splice(index, 1)
				}
				this.searchHistory.unshift(key)
				
				// 限制历史记录数量
				if (this.searchHistory.length > 10) {
					this.searchHistory = this.searchHistory.slice(0, 10)
				}
				
				try {
					uni.setStorageSync('searchHistory', JSON.stringify(this.searchHistory))
				} catch (e) {
					console.error('保存搜索历史失败：', e)
				}
			},
			// 清空搜索历史
			clearHistory() {
				this.searchHistory = []
				try {
					uni.removeStorageSync('searchHistory')
				} catch (e) {
					console.error('清空搜索历史失败：', e)
				}
			},
			// 使用历史记录或热门搜索项
			useHistoryItem(item) {
				this.searchKey = item
				this.showSearchPanel = false
				this.onSearch()
			},
			// 清空搜索
			clearSearch() {
				this.searchKey = ''
				this.showSearchPanel = false
			},
			// 搜索处理函数
			onSearch() {
				// 使用防抖，300ms内只执行最后一次搜索
				this.debounce(() => {
					// 如果搜索关键词不为空，保存到历史记录
					if (this.searchKey.trim()) {
						this.saveSearchHistory()
						
						// TODO: 这里调用后端搜索接口
						// 示例：this.searchProducts(this.searchKey)
						console.log('执行搜索，关键词：', this.searchKey)
					}
				}, 300)
			},
			// 实际的搜索请求函数
			async searchProducts(keyword) {
				try {
					// TODO: 调用后端接口
					// const res = await this.$http.get('/api/products/search', {
					//     params: { keyword }
					// })
					// this.productList = res.data
					
					// 目前使用本地过滤模拟搜索效果
					this.productList = this.productList.filter(item => 
						item.title.toLowerCase().includes(keyword.toLowerCase()) ||
						item.desc.toLowerCase().includes(keyword.toLowerCase())
					)
				} catch (e) {
					console.error('搜索失败：', e)
					uni.showToast({
						title: '搜索失败，请重试',
						icon: 'none'
					})
				}
			},
			// 切换排序方式
			changeSort(type) {
				if (this.currentSort === type) {
					if (type === 'price') {
						this.priceSort = this.priceSort === 'asc' ? 'desc' : 'asc'
					}
				} else {
					this.currentSort = type
					this.priceSort = 'asc'
				}
				
				// 重置列表
				this.page = 1
				this.productList = []
				this.hasMore = true
				this.getProductList()
			},
			// 加载更多
			loadMore() {
				if (!this.searchKey) {
					this.getProductList()
				}
			},
			// 跳转商品详情
			goDetail(item) {
				uni.navigateTo({
					url: `/pages/product/detail?id=${item.id}`
				})
			},
			// 切换子分类
			changeSubCategory(item) {
				if (this.currentSubCategory === item.id) return
				this.currentSubCategory = item.id
				// 重置列表
				this.page = 1
				this.productList = []
				this.hasMore = true
				this.getProductList()
			},
			// 从更多分类中选择
			selectMoreCategory(item) {
				this.showMoreCategories = false
				this.changeSubCategory(item)
			}
		}
	}
</script>

<style lang="scss">
	.container {
		min-height: 100vh;
		background: #f5f5f5;
	}
	
	.ip-info {
		position: relative;
		height: 300rpx;
		margin-bottom: 20rpx;
		
		.ip-banner {
			width: 100%;
			height: 100%;
		}
		
		.ip-content {
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			padding: 20rpx;
			background: linear-gradient(to top, rgba(0,0,0,0.7), transparent);
			
			.name {
				font-size: 36rpx;
				font-weight: bold;
				color: #fff;
				margin-bottom: 10rpx;
				display: block;
			}
			
			.desc {
				font-size: 24rpx;
				color: rgba(255,255,255,0.8);
			}
		}
	}
	
	.search-bar {
		background: #fff;
		padding: 20rpx;
		margin-bottom: 20rpx;
		position: relative;
		
		.search-input {
			position: relative;
			
			input {
				width: 100%;
				height: 72rpx;
				background: #f5f5f5;
				border-radius: 36rpx;
				padding: 0 80rpx 0 30rpx;
				font-size: 28rpx;
				color: #333;
				
				&::placeholder {
					color: #999;
				}
			}
			
			.clear-btn {
				position: absolute;
				right: 20rpx;
				top: 50%;
				transform: translateY(-50%);
				width: 40rpx;
				height: 40rpx;
				line-height: 40rpx;
				text-align: center;
				font-size: 32rpx;
				color: #999;
				background: #ddd;
				border-radius: 50%;
			}
		}
		
		.search-panel {
			position: absolute;
			top: 100%;
			left: 0;
			right: 0;
			background: #fff;
			padding: 20rpx;
			box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
			z-index: 100;
			
			.search-section {
				margin-bottom: 30rpx;
				
				.section-header {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20rpx;
					
					.title {
						font-size: 28rpx;
						color: #333;
						font-weight: bold;
					}
					
					.clear {
						font-size: 24rpx;
						color: #999;
					}
				}
				
				.tag-list {
					display: flex;
					flex-wrap: wrap;
					margin: 0 -10rpx;
					
					.tag-item {
						padding: 10rpx 20rpx;
						background: #f5f5f5;
						border-radius: 30rpx;
						font-size: 24rpx;
						color: #666;
						margin: 0 10rpx 10rpx;
						
						&:active {
							background: #e5e5e5;
						}
					}
				}
			}
		}
	}
	
	.filter-bar {
		display: flex;
		background: #fff;
		padding: 20rpx;
		margin-bottom: 20rpx;
		
		.filter-item {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 28rpx;
			color: #333;
			position: relative;
			
			&.active {
				color: #ff0000;
				
				&::after {
					content: '';
					position: absolute;
					bottom: -20rpx;
					left: 50%;
					transform: translateX(-50%);
					width: 40rpx;
					height: 4rpx;
					background: #ff0000;
					border-radius: 2rpx;
				}
			}
			
			.iconfont {
				font-size: 24rpx;
				margin-left: 4rpx;
			}
		}
	}
	
	.product-list {
		height: calc(100vh - 520rpx);
		padding: 20rpx;
		
		.waterfall-wrapper {
			display: flex;
			justify-content: space-between;
			margin: 0 -8rpx;
			
			.waterfall-column {
				flex: 1;
				padding: 0 8rpx;
			}
		}
		
		.product-item {
			background: #fff;
			border-radius: 20rpx;
			overflow: hidden;
			margin-bottom: 16rpx;
			box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
			position: relative;
			
			&:active {
				transform: scale(0.98);
			}
			
			image {
				width: 100%;
				height: auto;
				display: block;
				border-radius: 20rpx 20rpx 0 0;
			}
			
			.product-info {
				padding: 16rpx;
				
				.title {
					font-size: 26rpx;
					color: #333;
					line-height: 1.4;
					margin-bottom: 8rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
					font-weight: bold;
				}
				
				.desc {
					font-size: 22rpx;
					color: #666;
					line-height: 1.4;
					margin-bottom: 8rpx;
					display: -webkit-box;
					-webkit-box-orient: vertical;
					-webkit-line-clamp: 2;
					overflow: hidden;
				}
				
				.price-box {
					margin-bottom: 8rpx;
					display: flex;
					align-items: baseline;
					
					.price {
						font-size: 30rpx;
						color: #ff2442;
						font-weight: bold;
						margin-right: 8rpx;
						
						&::before {
							content: '¥';
							font-size: 24rpx;
							margin-right: 2rpx;
						}
					}
					
					.original-price {
						font-size: 22rpx;
						color: #999;
						text-decoration: line-through;
						
						&::before {
							content: '¥';
							margin-right: 2rpx;
						}
					}
				}
				
				.product-meta {
					display: flex;
					align-items: center;
					font-size: 22rpx;
					color: #999;
					
					.sales {
						margin-right: 16rpx;
						position: relative;
						
						&::after {
							content: '';
							position: absolute;
							right: -8rpx;
							top: 50%;
							transform: translateY(-50%);
							width: 1px;
							height: 12rpx;
							background: #eee;
						}
					}
					
					.stock {
						color: #666;
					}
				}
			}
		}
		
		.loading-more,
		.no-more,
		.no-result {
			text-align: center;
			padding: 20rpx;
			font-size: 24rpx;
			color: #999;
		}
	}
	
	// 修改商品图片比例
	.product-item {
		.site-image {
			position: relative;
			padding-bottom: 133.33%; // 4:3比例
			
			image {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				object-fit: cover;
			}
		}
	}
	
	.sub-category {
		background: #fff;
		padding: 20rpx;
		margin-bottom: 20rpx;
		position: relative;
		
		.category-tags {
			display: flex;
			align-items: center;
			
			.tag-item {
				padding: 12rpx 24rpx;
				margin-right: 20rpx;
				border-radius: 26rpx;
				font-size: 26rpx;
				color: #666;
				background: #f5f5f5;
				transition: all 0.3s;
				
				&.active {
					color: #fff;
					background: #ff2442;
				}
				
				&.more-btn {
					display: flex;
					align-items: center;
					margin-right: 0;
					
					.arrow-down {
						font-size: 20rpx;
						margin-left: 6rpx;
					}
				}
			}
		}
		
		.more-categories {
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 1000;
			
			.mask {
				position: absolute;
				top: 0;
				left: 0;
				right: 0;
				bottom: 0;
				background: rgba(0, 0, 0, 0.5);
			}
			
			.content {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				width: 600rpx;
				background: #fff;
				border-radius: 20rpx;
				padding: 30rpx;
				
				.title {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
					text-align: center;
					margin-bottom: 30rpx;
				}
				
				.category-grid {
					display: grid;
					grid-template-columns: repeat(3, 1fr);
					gap: 20rpx;
					
					.grid-item {
						height: 80rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						background: #f5f5f5;
						border-radius: 12rpx;
						font-size: 26rpx;
						color: #666;
						
						&.active {
							color: #fff;
							background: #ff2442;
						}
					}
				}
			}
		}
	}
</style> 